package com.cool4j.generator.builder

import com.cool4j.generator.entity.Table
import com.cool4j.generator.exception.ExceptionMessage
import com.cool4j.generator.util.DateUtil
import com.cool4j.generator.util.GeneratorUtil
import com.cool4j.generator.util.LogUtil
import com.cool4j.view.entity.HandlerVO
import freemarker.template.Configuration
import freemarker.template.Template
import freemarker.template.TemplateException

/**
 * common 包构造器类
 *
 * @author Frank create on 16/1/8 10:32
 */
class CommonBuilder extends BaseBuilder {

    private void createCommon(Configuration config, Map<String, Object> tableData, String className,
                              String packageName, String tempName, String outputPath) throws IOException, TemplateException {
        /* 获取或创建一个模板 */
        Template template = config.getTemplate(tempName, "UTF-8")
        def filePath = outputPath + "/" + packageName + "/" + className + ".java"
        GeneratorUtil.writeFile(filePath, template, tableData)
    }

    @Override
    protected getDataMap(Table table, String packagePath, HandlerVO handlerVO) {
        def dataMap = new HashMap<String, Object>()
        dataMap.put("commonPackage", handlerVO.getCommonPackage())
        dataMap.put("author", handlerVO.getAuthor())
        dataMap.put("currentDate", DateUtil.currentDateForComment)
        return dataMap
    }

    @Override
    boolean builder(Table table, String packagePath, HandlerVO handlerVO, Configuration config) {
        def dataMap = getDataMap(null, null, handlerVO)
        def outputPath = handlerVO.getOutputPath()
        try {
            createCommon(config, dataMap, "BaseDao", "common", "BaseDao.ftl", outputPath)
            createCommon(config, dataMap, "BaseParam", "common", "BaseParam.ftl", outputPath)
            createCommon(config, dataMap, "DynamicSqlSessionDaoSupport", "common", "DynamicSqlSessionDaoSupport.ftl", outputPath)
            createCommon(config, dataMap, "Page", "common", "Page.ftl", outputPath)
        } catch (IOException e) {
            LogUtil.logging(ExceptionMessage.LOG_COMMON_BUILDER_IO_EXCEPTION, e)
            return false
        } catch (TemplateException e) {
            LogUtil.logging(ExceptionMessage.LOG_COMMON_BUILDER_TEMPLATE_EXCEPTION, e)
            return false
        } catch (Exception e) {
            LogUtil.logging(ExceptionMessage.LOG_COMMON_BUILDER_OTHER_EXCEPTION, e)
            return false
        }
        return true
    }
}
